package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.views.RenewClassRecord;
import com.xmy.cultivate.service.*;
import com.xmy.cultivate.util.*;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.*;

/**
 * <p>
 * 员工 前端控制器
 * </p>
 *
 * @author min
 * @since 2022-07-19
 */
@RestController
@RequestMapping("/api/staff")
public class StaffController extends BaseController {

    @Autowired
    IdWorker idWorker;

    @Autowired
    IStaffService iStaffService;

    @Autowired
    IAdminService iAdminService;

    @Autowired
    IDictService iDictService;

    @Autowired
    @Lazy
    ITranscriptService iTranscriptService;

    @Autowired
    IQuarterService quarterService;

    @Autowired
    IRenewClassService iRenewClassService;

    @Autowired
    IRecordCourseService iRecordCourseService;

    @Autowired
    IStaffRankingDetailService iStaffRankingDetailService;

    @Autowired
    IStaffDataService iStaffDataService;

    @Autowired
    IOrganizationService iOrganizationService;

    @Autowired
    IRoleService iRoleService;

    @Autowired
    IQuarterService iQuarterService;

    @Autowired
    @Lazy
    IStaffRegService iStaffRegService;

    @Autowired
    @Lazy
    IStaffPermissionService iStaffPermissionService;

    @Autowired
    @Lazy
    IRoleAdminService iRoleAdminService;

    @Autowired
    @Lazy
    IRolePermissionService iRolePermissionService;

    @Autowired
    IPermissionService iPermissionService;

    @Autowired
    IMobileStaffPermissionService iMobileStaffPermissionService;

    @Autowired
    ITeacherLeadsYearClassService iTeacherLeadsYearClassService;

    @Autowired
    IMqPushService iMqPushService;

    @GetMapping()
    public Result findAll(@RequestParam Map reMap,
                          @RequestParam(required = false) String[] schoolIdList,
                          @RequestParam(required = false) String justType,
                          @RequestParam(name = "isExport", defaultValue = "0") Integer isExport,//是否为导出，0否1是
                          @RequestParam(name = "idList", required = false) List<Long> idList
    ) throws IOException {
        Integer pageNum = StringUtils.isEmpty((String) reMap.get("pageNum")) ? 1 : Integer.valueOf((String) reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String) reMap.get("pageSize")) ? 10 : Integer.valueOf((String) reMap.get("pageSize"));

        IPage<Staff> page = new Page<>(pageNum, pageSize);
        String departmentId = (String) reMap.get("departmentId");//所属部门id
        String isTeacher = (String) reMap.get("isTeacher");//是否上课老师
        String schoolId = (String) reMap.get("schoolId");//管辖校区
        String roleId = (String) reMap.get("roleId");//角色
        String status = (String) reMap.get("status");//状态

        String name = (String) reMap.get("name");


        QueryWrapper<Staff> staffQueryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(departmentId)) {
            staffQueryWrapper.inSql("id", "select for_id from appoint_school where type = 3 and school_id = " + departmentId);
        }

        staffQueryWrapper.eq(StringUtils.isNotBlank(isTeacher), "is_teacher", isTeacher);
        staffQueryWrapper.eq(StringUtils.isNotBlank(status), "status", status);
        staffQueryWrapper.eq(StringUtils.isNotBlank(justType), "just_type", justType);

        if (schoolIdList != null && schoolIdList.length > 0) {
            String schoolIdStr = "";
            schoolIdStr = org.apache.tomcat.util.buf.StringUtils.join(schoolIdList);
            staffQueryWrapper.inSql("admin_id", "select for_id from appoint_school where  type =2 and school_id in (" + schoolIdStr + ")");
        }

        if (StringUtils.isNotBlank(schoolId)) {
            staffQueryWrapper.eq("school_id", schoolId);
        }

        if (StringUtils.isNotBlank(roleId)) {
            staffQueryWrapper.inSql("id", "select admin_id from role_admin where role_id = " + roleId);
        }

        if (StringUtils.isNotBlank(name)) {
            staffQueryWrapper.like("name", name);
        }

        staffQueryWrapper.eq("deleted", 0);

        if (idList != null && idList.size() > 0) {
            staffQueryWrapper.in("id", idList);
        }

        staffQueryWrapper.orderByAsc("status","id");

        iStaffService.findAll(page, staffQueryWrapper);

        if (isExport == 1) {

            List<String> headList = new ArrayList<>();
            headList.add("员工姓名");
            headList.add("性别");
            headList.add("联系方式");
            headList.add("所属部门");
            headList.add("是否教师");
            headList.add("人事状态");
            headList.add("机构账号");

            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("员工信息");
            CellStyle headerCellStyle = workbook.createCellStyle();
            Font headerFont = workbook.createFont();
            headerFont.setFontHeightInPoints((short) 11);
            headerCellStyle.setFont(headerFont);
            headerCellStyle.setAlignment(HorizontalAlignment.CENTER);
            headerCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            Row headerRow = sheet.createRow(0);
            sheet.createFreezePane(0, 1);// 冻结首行

            for (int i = 0; i < headList.size(); i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headList.get(i));
                cell.setCellStyle(headerCellStyle);
            }

            CellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setFont(headerFont);
            cellStyle.setAlignment(HorizontalAlignment.CENTER);
            cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

            int rowIndex = 1; // 数据行起始索引

            for (Staff staff : page.getRecords()) {
                Row row = sheet.createRow(rowIndex);

                Cell cell = row.createCell(0);
                cell.setCellValue(staff.getName());
                sheet.setColumnWidth(0, 30 * 256);
                cell.setCellStyle(cellStyle);

                Cell cell1 = row.createCell(1);
                cell1.setCellValue(staff.getSex().getValue());
                sheet.setColumnWidth(1, 20 * 256);
                cell1.setCellStyle(cellStyle);

                Cell cell2 = row.createCell(2);
                cell2.setCellValue(staff.getPhone());
                sheet.setColumnWidth(2, 30 * 256);
                cell2.setCellStyle(cellStyle);

                String departName = "";
                if (staff.getDepartIdList() != null) {
                    for (Long id : staff.getDepartIdList()) {
                        departName += iOrganizationService.getById(id).getName();
                        if (!departName.equals("")) {
                            departName += "、";
                        }
                    }
                }
                Cell cell3 = row.createCell(3);
                cell3.setCellValue(departName);
                sheet.setColumnWidth(3, 15 * 256);
                cell3.setCellStyle(cellStyle);

                Cell cell4 = row.createCell(4);
                if (staff.getIsTeacher() == 1) {
                    cell4.setCellValue("是");
                } else {
                    cell4.setCellValue("否");
                }
                sheet.setColumnWidth(4, 15 * 256);
                cell4.setCellStyle(cellStyle);

                Cell cell5 = row.createCell(5);
                cell5.setCellValue(staff.getStatus().getValue());
                sheet.setColumnWidth(5, 20 * 256);
                cell5.setCellStyle(cellStyle);

                Cell cell6 = row.createCell(6);
                String roleName = "";
                String account = "";
                if (staff.getAdminObj() != null) {
                    account = staff.getAdminObj().getAccount();
                    if (staff.getAdminObj().getRoleList() != null && staff.getAdminObj().getRoleList().size() > 0) {
                        roleName = "（";
                        for (Role role : staff.getAdminObj().getRoleList()) {
                            roleName += role.getName();
                        }
                        roleName += ")";
                    }
                }
                cell6.setCellValue(account + roleName);
                sheet.setColumnWidth(6, 35 * 256);
                cell6.setCellStyle(cellStyle);

                rowIndex++;
            }

            String fileName = "员工信息" + ".xls";
            String encodedFileName = URLEncoder.encode(fileName, "UTF-8");
            response.setContentType("application/zip");//设置为zip格式
            response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);//设置响应头

            // 获取响应输出流
            OutputStream outputStream = response.getOutputStream();

            // 将工作簿写入输出流
            workbook.write(outputStream);

            // 关闭工作簿
            workbook.close();

            // 刷新输出流
            outputStream.flush();

            //关闭输出流
            outputStream.close();

        }

        return new Result(Code.OK, new PageResult<>(page.getRecords(), page.getTotal(), page.getPages()));
    }

    @GetMapping("staffList")
    public Result staffList( @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
                             @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize){
        IPage<Staff> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Staff> staffQueryWrapper = new QueryWrapper<>();
        staffQueryWrapper.eq("status", 1);
        staffQueryWrapper.eq("is_teacher", 1);
        staffQueryWrapper.eq("deleted", 0);
        List<Staff> staffList = iStaffService.list(staffQueryWrapper);
        return new Result(Code.OK, staffList, "查询成功");
//        iStaffService.page(page, staffQueryWrapper);
//        return new Result(Code.OK, new PageResult(page.getRecords(), page.getTotal(), page.getPages()));

    }


    @GetMapping("checkTeacher")
    public Result checkTeacher(
            @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", required = false, defaultValue = "100") Integer pageSize,
            @RequestParam(value = "isTeacher", required = false, defaultValue = "1") String isTeacher,
            @RequestParam(value = "name", required = false, defaultValue = "") String name,
            @RequestParam(value = "status", required = false, defaultValue = "1") String status,
            @RequestParam(value = "subjectId", required = false) String subjectId,
            @RequestParam(value = "schoolIdList", defaultValue = "") String[] schoolIdList
    ) {
        IPage<Staff> page = new Page<>(pageNum, pageSize);

        QueryWrapper<Staff> staffQueryWrapper = new QueryWrapper<>();
        if (!isTeacher.equals("0")) {
            staffQueryWrapper.eq("is_teacher", isTeacher);
        }
        staffQueryWrapper.inSql(StringUtils.isNotBlank(status), "status", status);
        if (schoolIdList.length > 0) {
            String schoolIdStr = String.join(",", schoolIdList);
//            staffQueryWrapper.and(i -> i.eq("scope_class_mode", 1).or().inSql("id", "select for_id from appoint_school where type=4 and school_id in(" + schoolIdStr + ")"));
            staffQueryWrapper.inSql("school_id", schoolIdStr);
        } else {
            //System.out.print("baseSchoolIdStr:"+baseSchoolIdStr);
            if (!isTeacher.equals("0")) {
//                staffQueryWrapper.and(i -> i.eq("scope_class_mode", 1).or().inSql("id", "select for_id from appoint_school where type=4 and school_id in(" + this.baseSchoolIdStr + ")"));
            }
            staffQueryWrapper.inSql("school_id", this.baseSchoolIdStr);
        }

        if (StringUtils.isNotBlank(name)) {
            staffQueryWrapper.like("name", name);
        }
        if (StringUtils.isNotBlank(subjectId)) {
            staffQueryWrapper.apply(StringUtils.isNotBlank(subjectId), "(find_in_set( " + subjectId + ", sigin_subjects ))");
        }
        staffQueryWrapper.eq("deleted", 0);
        iStaffService.findAll(page, staffQueryWrapper);
        return new Result(Code.OK, new PageResult(page.getRecords(), page.getTotal(), page.getPages()));
    }

    @GetMapping("/searchOne")
    public Result searchOne(@RequestParam Map reMap, @RequestParam(value = "teacherIdList", defaultValue = "") String[] teacherIdList) {

        String name = (String) reMap.get("name");
        QueryWrapper<Staff> staffQueryWrapper = new QueryWrapper<>();
        staffQueryWrapper.like(StringUtils.isNotBlank(name), "name", name);
        if (teacherIdList.length > 0) {
            staffQueryWrapper.notIn("id", teacherIdList);
        }
        List<Staff> staffList = new ArrayList<>();

        if (StringUtils.isNotBlank(name)) {
            staffList = iStaffService.list(staffQueryWrapper);
        }
        return new Result(Code.OK, new PageResult(staffList, (long) staffList.size(), 1L));

    }

    @GetMapping("/{id}")
    public Result findById(@PathVariable(value = "id") Long id) {
        Staff staff = iStaffService.findOneById(id);

        //自动排班年级
        TeacherLeadsYearClass teacherLeadsYearClass = iTeacherLeadsYearClassService.getAutoYearClassList(String.valueOf(id));
//        if (teacherLeadsYearClass != null && teacherLeadsYearClass.getYearClassIds() != null){
//            staff.setYearClassIds(teacherLeadsYearClass.getYearClassIds());
//        }
        ArrayList<TeacherLeadsYearClass> teacherLeadsYearClassLists = new ArrayList<>();
        if (teacherLeadsYearClass != null && teacherLeadsYearClass.getYearClassIds() != null) {
            String yearClassIds = teacherLeadsYearClass.getYearClassIds();
            String[] split = yearClassIds.split(",");
            // 使用 Set 去重
            Set<Integer> uniqueYearClassIds = new HashSet<>();
            for (String yearClassId : split) {
                uniqueYearClassIds.add(Integer.valueOf(yearClassId));
            }

            // 将去重后的年级ID转换为 TeacherLeadsYearClass 对象
            for (Integer yearClassId : uniqueYearClassIds) {
                TeacherLeadsYearClass tlyc = new TeacherLeadsYearClass();
                tlyc.setYearClassId(yearClassId);
                tlyc.setYearClassName(ConfigData.getYearClassForNum(yearClassId));
                // 如果需要设置其他字段，可以在这里进行设置
                teacherLeadsYearClassLists.add(tlyc);
            }
        }
        staff.setTeacherLeadsYearClassList(teacherLeadsYearClassLists);

        ArrayList<Integer> teacherLeadsYearClassIdList = new ArrayList<>();
        List<TeacherLeadsYearClass> teacherLeadsYearClassList = iTeacherLeadsYearClassService.getTeacherLeadsYearClass(String.valueOf(id));
        for (TeacherLeadsYearClass item : teacherLeadsYearClassList) {
            teacherLeadsYearClassIdList.add(item.getYearClassId());
        }
        staff.setTeacherLeadsYearClassIdList(teacherLeadsYearClassIdList);
//        if (teacherLeadsYearClassList != null){
//            staff.setTeacherLeadsYearClassList(teacherLeadsYearClassList);
//        }
        //long ids =  idWorker.nextId();
        //System.out.println(ids);
        return new Result(Code.OK, staff);
    }


    @PostMapping()
    public Result save(@RequestBody Staff staff) {
        //dict.setId(idWorker.nextId());
        boolean rs = iStaffService.saveTo(staff);
        if (rs && staff.getRegId() != null) {
            //更改新注册状态 2024.4.30
            StaffReg staffRegServiceOne = iStaffRegService.getById(staff.getRegId());
            staffRegServiceOne.setStatus(1);
            iStaffRegService.updateById(staffRegServiceOne);
        }

        // 增加财务权限
        iStaffPermissionService.updateStaffPermissionByStaffId(String.valueOf(staff.getId()), staff.getStaffPermissionList());
        // 增加教务权限
        iMobileStaffPermissionService.updateStaffPermissionByStaffId(String.valueOf(staff.getId()), staff.getMobileStaffPermissionList());

        // 同步账号
        iMqPushService.syncUpdateStaff(staff);

        return new Result(rs ? Code.OK : Code.ERROR);
    }


    @PutMapping("/{id}")
    public Result update(@PathVariable(value = "id") String id, @RequestBody Staff staff) {
        boolean rs = iStaffService.updateTo(staff);

        // 增加财务权限
        iStaffPermissionService.updateStaffPermissionByStaffId(String.valueOf(staff.getId()), staff.getStaffPermissionList());
        // 增加教务权限
        iMobileStaffPermissionService.updateStaffPermissionByStaffId(String.valueOf(staff.getId()), staff.getMobileStaffPermissionList());

        // 离职老师同步带班学员数据
        if (staff.getStatus().getKey() == 2) {
            iMqPushService.leaveTeacherStudentByStatus(staff.getId());
        }

        // 同步账号
        staff.getAdminObj().setPwd(null);
        staff.getAdminObj().setPwdShow(null);
        iMqPushService.syncUpdateStaff(staff);

        return new Result(rs ? Code.OK : Code.ERROR);
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable(value = "id") Long id) {
        boolean rs = iStaffService.removeById(id);
        iAdminService.removeById(id);

        // 删除员工后财务个人权限表相关数据清空
        iStaffPermissionService.remove(new QueryWrapper<StaffPermission>().eq("staff_id", id));
        // 删除员工后教务个人权限表相关数据清空
        iMobileStaffPermissionService.remove(new QueryWrapper<MobileStaffPermission>().eq("staff_id", id));

        return new Result(rs ? Code.OK : Code.ERROR);
    }

    @GetMapping("/working")
    @ApiOperation("工龄")
    public Result listQueryRanking(@RequestParam Map reMap) {
        Integer pageNum = StringUtils.isEmpty((String) reMap.get("pageNum")) ? 1 : Integer.valueOf((String) reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String) reMap.get("pageSize")) ? 10 : Integer.valueOf((String) reMap.get("pageSize"));
        String name = (String) reMap.get("name");
        String status = (String) reMap.get("status");
        String role = (String) reMap.get("roleId");

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(name), "staff.`name`", name);
        queryWrapper.eq(StringUtils.isNotBlank(status), "staff.`status`", status);
        queryWrapper.eq(StringUtils.isNotBlank(role), "role_admin.role_id", role);
        queryWrapper.ne("staff.`name`", "111");
        queryWrapper.notLike("staff.name", "前台");
        queryWrapper.notLike("staff.name", "市场部");
        queryWrapper.notLike("staff.name", "总部");
        queryWrapper.isNotNull("`status`");
        queryWrapper.notLike("staff.`name`", "校区");

        List<Staff> staffList = iStaffService.working(queryWrapper);

        List<Map<String, Object>> mapList = new ArrayList<>();

        for (Staff staff : staffList) {
            Integer days = staff.getWorking();
            if (days != null) {
                if (days != 0) {
                    int years = days / 365; // 计算年份
                    int remainingDays = days % 365; // 计算剩余天数
                    int months = remainingDays / 30; // 计算月份
                    int day = months % 30;
                    if (years == 0) {
                        if (months == 0) {
                            staff.setWorkingStr(remainingDays + "天");
                        } else {
                            staff.setWorkingStr(months + "月" + day + "天");
                        }
                    } else {
                        if (months == 0) {
                            staff.setWorkingStr(years + "年" + months + "月" + remainingDays + "天");
                        } else {
                            staff.setWorkingStr(years + "年" + months + "月" + day + "天");
                        }
                    }
                }
            }

            HashMap map = new HashMap<>();
            map.put("name", staff.getName());
            map.put("status", staff.getStatus());
            map.put("entryDate", staff.getEntryDate());
            map.put("leaveDate", staff.getLeaveDate());
            map.put("working", staff.getWorking());
            map.put("workingStr", staff.getWorkingStr());
            mapList.add(map);
        }

        Page<Map<String, Object>> page = new Page<>(pageNum, pageSize, mapList.size()); // 初始化 Page 对象
        Integer newPage = pageSize * (pageNum - 1);
        Integer endPage = pageSize * pageNum;
        if (pageSize * pageNum > mapList.size()) {
            endPage = mapList.size();
        }
        page.setRecords(mapList.subList(newPage, endPage)); // 设置记录列表
        page.setPages(pageNum); // 设置总页数

        return new Result(Code.OK, new PageResult(page.getRecords(), page.getTotal(), page.getPages()), "工龄查询完成");
    }

    @GetMapping("/analyse")
    @ApiOperation("人员分析")
    public Result staffAnalyse(@RequestParam Map reMap) {
        Integer pageNum = StringUtils.isEmpty((String) reMap.get("pageNum")) ? 1 : Integer.valueOf((String) reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String) reMap.get("pageSize")) ? 10 : Integer.valueOf((String) reMap.get("pageSize"));

        String name = (String) reMap.get("name");
        String year = (String) reMap.get("year");
        String quarterNum = (String) reMap.get("quarterNum");
        String schoolId = (String) reMap.get("schoolId");
        String roleId = (String) reMap.get("roleId");
        String subjectId = (String) reMap.get("subjectId");

        List<Staff> staffList = iStaffService.staffAnalyse(quarterNum, year, roleId, name, schoolId, subjectId);
        List<HashMap<String, Object>> mapList = new ArrayList<>();

        StringBuffer teacherSb = new StringBuffer();

        Integer staffListCount = staffList.size();

        if (staffList != null && staffListCount != 0) {
            Integer count = 0;
            for (Staff staff : staffList) {
                count++;
                teacherSb.append(staff.getId());
                if (count < staffListCount) {
                    teacherSb.append(",");
                }
            }
        } else {
            teacherSb.append("0");
        }

        String teacherStr = String.valueOf(teacherSb);

        /**
         * 填写的内容显示
         */
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("year_part", year);
        wrapper.eq("quarter_num", quarterNum);
        wrapper.inSql("teacher_id", teacherStr);
        wrapper.inSql(StringUtils.isNotBlank(schoolId), "school_id", schoolId);
        wrapper.inSql("(teacher_id, id)", "SELECT teacher_id, MAX(id) FROM `staff_data` GROUP BY teacher_id");
        wrapper.orderByDesc("id");

        List<StaffData> staffDataList = iStaffDataService.list(wrapper);

        /**
         * 工号排名
         */
        wrapper.clear();
        if (quarterNum != null) {
            wrapper.eq("year_part", year);
            wrapper.eq("num", quarterNum);
            Quarter quarter = quarterService.getOne(wrapper);
            wrapper.clear();
            try {
                wrapper.ge("ranking_date", quarter.getStartDate());
                wrapper.le("ranking_date", quarter.getEndDate());
            } catch (Exception ex) {
                return new Result(Code.ERROR, "", "当前年份季度不存在");
            }
        }

        wrapper.like(StringUtils.isNotBlank(name), "staff_ranking_detail.staff_name", name);
        wrapper.eq(StringUtils.isNotBlank(year), "DATE_FORMAT(ranking_date,'%Y')", year);
        wrapper.eq("staff_ranking.deleted", 0);
        wrapper.eq("staff_ranking_detail.deleted", 0);
        wrapper.inSql("staff_id", teacherStr);
        List<StaffRankingDetail> staffRankingDetails = iStaffRankingDetailService.staffAnalysis(wrapper);

        /**
         * 缴费率
         */
        String quarterNum1 = null;
        String quarterNum2 = null;

        String startDate1 = null;
        String endDate1 = null;

        List<RenewClassRecord> records1 = new ArrayList<>();
        List<RenewClassRecord> records2 = new ArrayList<>();

        wrapper.clear();
        if (quarterNum != null) {
            wrapper.eq("year_part", year);
            wrapper.eq("num", quarterNum);
            Quarter quarter = quarterService.getOne(wrapper);


            records1 = iRenewClassService.staffAnalysis(schoolId, year, quarterNum, subjectId, teacherStr);
            quarterNum1 = quarter.getName();
            startDate1 = String.valueOf(quarter.getStartDate());
            endDate1 = String.valueOf(quarter.getEndDate());

            wrapper.clear();
            if (quarterNum.equals("1")) {
                wrapper.eq("year_part", Integer.valueOf(year) - 1);
                wrapper.eq("num", 4);
                wrapper.orderByDesc("id");
                wrapper.last("LIMIT 1");
                Quarter previousQuarter = quarterService.getOne(wrapper);

                records2 = iRenewClassService.staffAnalysis(schoolId, String.valueOf(Integer.valueOf(year) - 1), String.valueOf(previousQuarter.getNum()), subjectId, teacherStr);
                quarterNum2 = previousQuarter.getName();

            } else {
                wrapper.eq("year_part", year);
                wrapper.eq("num", Integer.valueOf(quarterNum) - 1);
                Quarter previousQuarter = quarterService.getOne(wrapper);

                records2 = iRenewClassService.staffAnalysis(schoolId, year, String.valueOf(previousQuarter.getNum()), subjectId, teacherStr);

                quarterNum2 = previousQuarter.getName();
            }
        } else {
            wrapper.orderByDesc("id");
            wrapper.last("LIMIT 2");
            List<Quarter> quarters = quarterService.list(wrapper);
            if (quarters.size() >= 2) {
                records1 = iRenewClassService.staffAnalysis(schoolId, String.valueOf(quarters.get(0).getYearPart()), String.valueOf(quarters.get(0).getNum()), subjectId, teacherStr);
                records2 = iRenewClassService.staffAnalysis(schoolId, String.valueOf(quarters.get(1).getYearPart()), String.valueOf(quarters.get(1).getNum()), subjectId, teacherStr);

                startDate1 = String.valueOf(quarters.get(0).getStartDate());
                endDate1 = String.valueOf(quarters.get(0).getEndDate());

                quarterNum1 = quarters.get(0).getName();
                quarterNum2 = quarters.get(1).getName();
            }
        }


        /**
         * 补课人数
         */
        List<RepairLesson> repairLessons = iRecordCourseService.getRepairLesson(schoolId, year, quarterNum, subjectId, teacherStr);

        Map<Long, Integer> repairCountMap = new HashMap<>();

        for (RepairLesson repairLesson : repairLessons) {
            Long teacherId = repairLesson.getTeacherId();
            int allRepairCount = repairLesson.getAllRepairCount();
            repairCountMap.put(teacherId, allRepairCount);
        }

        /**
         * 招生数据
         */
        //邀约
        List<RepairLesson> recruitCount = iRecordCourseService.enrollmentData(schoolId, startDate1, endDate1, subjectId, String.valueOf(1), teacherStr);
        Map<Long, Double> recruitCountMap = new HashMap<>();
        for (RepairLesson lesson : recruitCount) {
            Long teacherId = lesson.getTeacherId();
            Double dealNum = lesson.getDealNum();
            recruitCountMap.put(teacherId, dealNum);
        }

        //试听
        List<RepairLesson> inviteCount = iRecordCourseService.enrollmentData(schoolId, startDate1, endDate1, subjectId, String.valueOf(2), teacherStr);
        Map<Long, Double> inviteCountMap = new HashMap<>();
        for (RepairLesson lesson : inviteCount) {
            Long teacherId = lesson.getTeacherId();
            Double dealNum = lesson.getDealNum();
            inviteCountMap.put(teacherId, dealNum);
        }

        //成交
        List<RepairLesson> concludeCount = iRecordCourseService.enrollmentData(schoolId, startDate1, endDate1, subjectId, String.valueOf(3), teacherStr);
        Map<Long, Double> concludeCountMap = new HashMap<>();
        for (RepairLesson lesson : concludeCount) {
            Long teacherId = lesson.getTeacherId();
            Double dealNum = lesson.getDealNum();
            concludeCountMap.put(teacherId, dealNum);
        }

        //校区
        List<Organization> organizations = iOrganizationService.list();
        Map<Long, String> organizationsMap = new HashMap<>();
        for (Organization organization : organizations) {
            organizationsMap.put(organization.getId(), organization.getName());
        }

        //角色
        List<Role> roles = iRoleService.list();
        Map<Long, String> rolesMap = new HashMap<>();
        for (Role role : roles) {
            rolesMap.put(role.getId(), role.getName());
        }

        /**
         * 安全值
         */
        //小学学段
        List<HashMap<String, Object>> scoreDataList1 = iTranscriptService.securityData(schoolId, subjectId, year, quarterNum, teacherStr, String.valueOf(1));
        //初中学段
        List<HashMap<String, Object>> scoreDataList2 = iTranscriptService.securityData(schoolId, subjectId, year, quarterNum, teacherStr, String.valueOf(2));

        /**
         * 返回数据
         */
        for (Staff staff : staffList) {
            Long teacherId = staff.getId();
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("teacherId", teacherId);
            hashMap.put("name", staff.getName());
            hashMap.put("subjectsId", staff.getSubjectsId());
            hashMap.put("quarterNum", quarterNum1);
            hashMap.put("year", year);
            hashMap.put("organization", organizationsMap.get(staff.getSchoolId()));
            hashMap.put("role", rolesMap.get(staff.getRoleId()));

            //填写的数据展示
            hashMap.put("advantage", "");
            hashMap.put("advantageCase", "");
            hashMap.put("deficiency", "");
            hashMap.put("deficiencyCase", "");
            hashMap.put("primaryScore", "");
            hashMap.put("highScore", "");
            hashMap.put("combineScore", "");

            Optional<StaffData> staffDataOptional = staffDataList.stream()
                    .filter(staffData -> staffData.getTeacherId().equals(teacherId))
                    .findFirst();

            staffDataOptional.ifPresent(staffData -> {
                hashMap.put("advantage", staffData.getAdvantage());
                hashMap.put("advantageCase", staffData.getAdvantageCase());
                hashMap.put("deficiency", staffData.getDeficiency());
                hashMap.put("deficiencyCase", staffData.getDeficiencyCase());
                hashMap.put("primaryScore", staffData.getPrimaryScore());
                hashMap.put("highScore", staffData.getHighScore());
                hashMap.put("combineScore", staffData.getCombineScore());
            });

            //安全值
            for (HashMap<String, Object> scoreData : scoreDataList1) {
                if (scoreData.get("teacherId").equals(teacherId)) {
                    hashMap.put("scoreData1", scoreData.get("scoreData"));
                }
            }
            for (HashMap<String, Object> scoreData : scoreDataList2) {
                if (scoreData.get("teacherId").equals(teacherId)) {
                    hashMap.put("scoreData2", scoreData.get("scoreData"));
                }
            }

            double scoreData1 = 0;
            double scoreData2 = 0;

            if (hashMap.containsKey("scoreData1")) {
                Object obj1 = hashMap.get("scoreData1");
                if (obj1 instanceof BigDecimal) {
                    scoreData1 = ((BigDecimal) obj1).setScale(2, RoundingMode.HALF_UP).doubleValue();
                } else if (obj1 instanceof Number) {
                    scoreData1 = ((Number) obj1).doubleValue();
                } else {
                    try {
                        scoreData1 = Double.parseDouble(obj1.toString());
                    } catch (NumberFormatException e) {

                    }
                }
            }

            if (hashMap.containsKey("scoreData2")) {
                Object obj2 = hashMap.get("scoreData2");
                if (obj2 instanceof BigDecimal) {
                    scoreData2 = ((BigDecimal) obj2).setScale(2, RoundingMode.HALF_UP).doubleValue();
                } else if (obj2 instanceof Number) {
                    scoreData2 = ((Number) obj2).doubleValue();
                } else {
                    try {
                        scoreData2 = Double.parseDouble(obj2.toString());
                    } catch (NumberFormatException e) {

                    }
                }
            }

            double scoreData3 = (scoreData1 + scoreData2) / 2;
            if (scoreData3 != 0.0) {
                DecimalFormat df = new DecimalFormat("#.00");
                hashMap.put("scoreData3", df.format(scoreData3));
            }

            //排位
            ArrayList<HashMap<String, Object>> staffRankingsArray = new ArrayList<>();
            for (StaffRankingDetail staffRankingDetail : staffRankingDetails) {
                if (staffRankingDetail.getStaffId().equals(teacherId)) {
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("name", staffRankingDetail.getStaffRankingName());
                    map.put("ranking", staffRankingDetail.getRankingNum());
                    staffRankingsArray.add(map);
                }
            }
            hashMap.put("staffRankings", staffRankingsArray);

            //补课人数
            int repairCount = repairCountMap.getOrDefault(teacherId, 0);
            hashMap.put("repairCount", repairCount);

            //招生数据
            hashMap.put("recruitCount", recruitCountMap.getOrDefault(teacherId, 0.00));
            hashMap.put("inviteCount", inviteCountMap.getOrDefault(teacherId, 0.00));
            hashMap.put("concludeCount", concludeCountMap.getOrDefault(teacherId, 0.00));

            //缴费率
            double totalPercentage1 = 0.0;
            double totalPercentage2 = 0.0;
            int count1 = 0;
            int count2 = 0;

            ArrayList<HashMap<String, Object>> recordsArray = new ArrayList<>();

            for (RenewClassRecord record : records1) {
                if (record.getTeacherId().equals(teacherId)) {
                    double percentage = (double) record.getBigFifteen() / (record.getBigFifteen() + record.getLittleFifteen()) * 100.0;
                    totalPercentage1 += percentage;
                    count1++;
                }
            }
            double averagePercentage1 = count1 > 0 ? totalPercentage1 / count1 : 0.0;

            HashMap<String, Object> recordsMap1 = new HashMap<>();
            recordsMap1.put("record", averagePercentage1);
            recordsMap1.put("quarterNum", quarterNum1);
            recordsArray.add(recordsMap1);

            for (RenewClassRecord record : records2) {
                if (record.getTeacherId().equals(teacherId)) {
                    double percentage = (double) record.getBigFifteen() / (record.getBigFifteen() + record.getLittleFifteen()) * 100.0;
                    totalPercentage2 += percentage;
                    count2++;
                }
            }

            double averagePercentage2 = count2 > 0 ? totalPercentage2 / count2 : 0.0;

            double averagePercentage = (averagePercentage1 + averagePercentage2) / 2;

            HashMap<String, Object> recordsMap2 = new HashMap<>();
            recordsMap2.put("record", averagePercentage2);
            recordsMap2.put("quarterNum", quarterNum2);
            recordsArray.add(recordsMap2);

            hashMap.put("records", recordsArray);
            hashMap.put("record", averagePercentage);

            mapList.add(hashMap);
        }

        Page<HashMap<String, Object>> page = new Page<>(pageNum, pageSize, mapList.size()); // 初始化 Page 对象
        Integer newPage = pageSize * (pageNum - 1);
        Integer endPage = pageSize * pageNum;
        if (pageSize * pageNum > mapList.size()) {
            endPage = mapList.size();
        }
        page.setRecords(mapList.subList(newPage, endPage)); // 设置记录列表
        page.setPages(pageNum); // 设置总页数

        return new Result(Code.OK, new PageResult(page.getRecords(), page.getTotal(), page.getPages()), "人员分析查询完成");
    }

    @PostMapping("/analyse")
    @ApiOperation("人员分析添加数据")
    public Result saveAnalyse(@RequestBody StaffData staffData) {
        boolean save = iStaffDataService.save(staffData);
        return new Result(save ? Code.SAVE_OK : Code.SAVE_ERROR, null, save ? Code.SAVE_OK_MSG : Code.SAVE_ERROR_MSG);
    }

    private double getScoreDataValue(List<HashMap<String, Object>> scoreDataList, String teacherId) {
        for (HashMap<String, Object> scoreData : scoreDataList) {
            if (scoreData.get("teacherId").equals(teacherId)) {
                Object data = scoreData.get("scoreData");
                if (data instanceof BigDecimal) {
                    return ((BigDecimal) data).setScale(2, RoundingMode.HALF_UP).doubleValue();
                } else {
                    return Double.parseDouble((String) data);
                }
            }
        }
        return 0; // 如果没有找到匹配的数据，返回默认值
    }

    @ApiOperation("批量转校-更换带班老师")
    @GetMapping("changeTeacher")
    public Result changeTeacher(@RequestParam Map<String, Object> reMap,
                                @RequestParam(value = "isTeacher", required = false, defaultValue = "1") String isTeacher,
                                @RequestParam(value = "schoolId", defaultValue = "") String schoolId) {
        String yearPart = reMap.get("yearPart") != null && !reMap.get("yearPart").toString().isEmpty() ? reMap.get("yearPart").toString() : "";
        String quarterNum = reMap.get("quarterNum") != null && !reMap.get("quarterNum").toString().isEmpty() ? reMap.get("quarterNum").toString() : "";
        Quarter quarterNow = iQuarterService.getNowQuarter();
        String subjectsId = reMap.get("subjectsId") != null && !reMap.get("subjectsId").toString().isEmpty() ? reMap.get("subjectsId").toString() : null;
        String status = "1";
        QueryWrapper<Staff> staffQueryWrapper = new QueryWrapper<>();
        if (!isTeacher.equals("0")) {
            staffQueryWrapper.eq("is_teacher", isTeacher);
        }
        staffQueryWrapper.eq(StringUtils.isNotBlank(status), "status", status);

        String name = (String) reMap.get("name");
        if (StringUtils.isNotBlank(name)) {
            staffQueryWrapper.like("name", name);
        }
        if (StringUtils.isBlank(yearPart)) {
            yearPart = quarterNow.getYearPart().toString();
        }
        if (StringUtils.isBlank(quarterNum)) {
            quarterNum = quarterNow.getNum().toString();
        }
        //staffQueryWrapper.inSql("id", "SELECT teacher_id FROM grade WHERE id IN (SELECT grade_id FROM student_grade WHERE year_part = " + yearPart + " AND quarter_num = " + quarterNum + " and school_id = "+schoolId+" AND deleted = 0 GROUP BY grade_id) AND deleted = 0 AND year_part = " + yearPart + " AND quarter_num = " + quarterNum + " GROUP BY teacher_id");

        String inSql = "select for_id from appoint_school where type =4 and deleted = 0 ";
        if (StringUtils.isNotBlank(schoolId)) {
            inSql += "and school_id =" + schoolId;
        }

        if (StringUtils.isNotBlank(subjectsId)) {
            List<Long> stuIdList = iStaffService.getTeacherIdForSubjects(subjectsId);
            staffQueryWrapper.in("id", stuIdList);
        }

        staffQueryWrapper.inSql("id", inSql);

        List<Staff> staffList = iStaffService.list(staffQueryWrapper);
        return new Result(Code.OK, new PageResult<>(staffList, (long) staffList.size(), 1L));
    }

    @PostMapping("/updateQyWeCharId")
    public Result updateQyWeCharId(@RequestBody Staff staff){
        Staff staffInfo = iStaffService.getById(staff.getId());
        //System.out.println("==================phone"+staffInfo.getPhone().length());
        if (staffInfo.getPhone().length() == 11){
            iMqPushService.updateQyWecharId(staffInfo);
            return new Result(Code.OK, "", "更新完成");
        }else {
            return new Result(Code.OK, "", "手机号不正确");
        }
    }

}